package com.evolutioninc.fortunecookie;

import java.io.IOException;
import java.util.Random;
import java.util.Stack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.ListPreference;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class fortunecookie extends Activity
{
    private TextView fortuneDisplayView;
    private Button getFortuneBtn;
    private Drawable defaultBackground;
    private String currentFortuneMode = "";
    private Vibrator vibe; 
    private ShakeListener mShaker;
    private Stack<String> oldFortuneStack = new Stack<String>();
    private MediaPlayer mp;
    private ChangeFortuneListener tw;
	private SharedPreferences preferences;
	private changePreferenceListener changePrefListener;
	
    public class ChangeFortuneListener implements TextWatcher
    {    	
		public void afterTextChanged(Editable s) {
			// Play sound if the setting is set to true
			if(preferences.getBoolean("sound", true))
				mp.start();
		}
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub
		}

		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
		}
    }

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mp = MediaPlayer.create(getApplicationContext(), R.raw.fv); 

		// Initialize preferences
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		preferences.registerOnSharedPreferenceChangeListener(changePrefListener = new changePreferenceListener());

        // Shake Listeners functions make the phone vibrate during shakes
        vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        mShaker = new ShakeListener(this);
        mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
        	public void onShake() {
    			if(preferences.getBoolean("shake", true)) {
    				vibe.vibrate(100);
        			pushOldFortune(fortuneDisplayView.getText().toString());
        			updateDisplay(getFortune());
    			}
        	}
        });

        // capture our View elements
        fortuneDisplayView = (TextView) findViewById(R.id.fortuneDisplay);
        fortuneDisplayView.addTextChangedListener(tw = new ChangeFortuneListener());
        getFortuneBtn = (Button) findViewById(R.id.getFortune);
        defaultBackground = getFortuneBtn.getBackground();

        //Default to normal mode (fortune cookies)
        setFortuneMode();
    }

    // Button listener 
    public void getFortune_OnClick(View v) throws IllegalStateException, IOException
    {
    	pushOldFortune(fortuneDisplayView.getText().toString());
        updateDisplay(getFortune());
    }

    // Updates the Fortune we display in the TextView
    private void updateDisplay(String fortune_str)
    {   
    	fortuneDisplayView.setText(fortune_str);
    }

    // Get fortune from the fortune database
    private String getFortune()
    {
    	Random rand = new Random();
    	String[] mode_array = getResources().getStringArray(R.array.fortune_mode);
    	String[] string_array = {""};
    	String quote = "";
    	
    	if(currentFortuneMode.equals(mode_array[0]))
    	{
    		string_array = getResources().getStringArray(R.array.fortune_array);
    	}
    	else if(currentFortuneMode.equals(mode_array[1]))
    	{
    		string_array = getResources().getStringArray(R.array.confucius_quotes);
    		quote = "Confucius Say...\n";
    	}
    	
    	quote = quote.concat(string_array[rand.nextInt(string_array.length)]);
    	
		return quote;
    }
    
    // Set the fortune Mode
    public void setFortuneMode()
    {
    	String[] mode_array = getResources().getStringArray(R.array.fortune_mode);
    	String Mode = preferences.getString("fortune_mode", mode_array[0]);

    	// Don't changed the mode if it is the same as the current one
    	if(currentFortuneMode.equals(Mode))
    		return;
    	
    	// Changed the mode

    	// Normal fortune cookie mode
    	if (Mode.equals(mode_array[0])) {
    		getFortuneBtn.setText("");
    		getFortuneBtn.setBackgroundResource(R.drawable.cookie_button);
    		updateDisplay(getString(R.string.normal_default));
    		currentFortuneMode = mode_array[0];
    		oldFortuneStack.clear();
    	}
    	// 
    	else if (Mode.equals(mode_array[1])) {
    		getFortuneBtn.setBackgroundDrawable(defaultBackground);
    		getFortuneBtn.setText(R.string.confucius_button);
    		updateDisplay(getString(R.string.confucius_default));
    		currentFortuneMode = mode_array[1];
    		oldFortuneStack.clear();
    	}	
    }
    
    // Get previous fortune from the stack
    private String popOldFortune()
    {
    	if(oldFortuneStack.empty())
    		return "No one is rich enough to buy back the past.";
    	
    	return oldFortuneStack.pop();
    }
    
    // Push a new item into the fortune stack
    private void pushOldFortune(String quote){
    	// Limits the size of the fortune stacks to 10
    	if(oldFortuneStack.size() >= 10){
    		oldFortuneStack.remove(0);
    	}

    	// Stored the fortune into the stack
    	oldFortuneStack.push(quote);
    }

/**
 * Functions for creating and defining the menu logics     
 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
			case R.id.prevfortune: {
	    		updateDisplay(popOldFortune());
	    		break;
	    	}        
    		case R.id.facebook: {
        		Toast.makeText(this, R.string.donate, Toast.LENGTH_LONG).show();
        		break;
        	}
        	case R.id.about: {
            	Toast.makeText(this, R.string.copyright, Toast.LENGTH_LONG).show();
            	break;
            }
        	case R.id.setting: {
        		Intent settingsActivity = new Intent(getBaseContext(),Preferences.class);
        		startActivity(settingsActivity);
        		break;
        	}
        }
        return true;
    }

    /**
     * Update Fortune Mode when the setting changed 
     * @author Kent Wong
     *
     */
    public class changePreferenceListener implements OnSharedPreferenceChangeListener{
    	
    	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
			// Let's do something a preference value changes
			if (key.equals("fortune_mode")) {
				setFortuneMode(); 
			}
    	}
	}

/**
 * Shaker listener functions
*/
    @Override
    public void onResume()
    {
      mShaker.resume();
      super.onResume();
    }
    
    @Override
    public void onPause()
    {
      mShaker.pause();
      super.onPause();
    }
}